package org.itboys.seller;

import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.itboys.admin.constant.AdminSessionConstant;
import org.itboys.basetemplate.service.IncomeRecordService;
import org.itboys.commons.CommonConstants.DF;
import org.itboys.commons.utils.ajax.AjaxUtils;
import org.itboys.commons.utils.servlet.ServletContextHolder;
import org.itboys.dto.SellerOrderListDto;
import org.itboys.framework.query.JsonPageUtils;
import org.itboys.framework.spring.controller.BaseController;
import org.itboys.mongodb.utils.page.Page;
import org.itboys.mongodb.utils.query.QueryParamUtils;
import org.itboys.trade.constant.OrderConstant;
import org.itboys.trade.entity.Order;
import org.itboys.trade.entity.OrderItem;
import org.itboys.trade.entity.TicketOrder;
import org.itboys.trade.entity.TicketOrderItem;
import org.itboys.trade.service.OrderItemService;
import org.itboys.trade.service.OrderService;
import org.itboys.trade.service.TicketOrderItemService;
import org.itboys.trade.service.TicketOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;



/**
 * Created by Administrator on 2016/7/7.
 */
@RestController
@RequestMapping("/seller/order")
public class SellerOrderController extends BaseController {
	@Autowired
	private OrderService orderService;
	@Autowired
	private TicketOrderService ticketOrderService;
	@Autowired
	private TicketOrderItemService ticketOrderItemService;
	@Autowired
	private OrderItemService itemService;
	@Autowired
	private IncomeRecordService incomeRecordService;
	@RequestMapping("/toListVM")
	public ModelAndView toListVM(HttpServletRequest request,HttpServletResponse response){
		return new ModelAndView("/order/list");
	}
	@RequestMapping("/toTicketListVM")
	public ModelAndView toTicketListVM(HttpServletRequest request,HttpServletResponse response){
		return new ModelAndView("/order/ticketList");
	}
	@RequestMapping("/list")
	public void list(HttpServletRequest request,HttpServletResponse response){
		Map<String, Object> sqlMap = QueryParamUtils.builderQueryMap(request);// 组装查询参数
		Long sellerId=(Long)request.getSession().getAttribute(AdminSessionConstant.SHOP_ID);
		sqlMap.put("pageNo", Integer.valueOf(request.getParameter("page")));
		sqlMap.put("pageSize", Integer.valueOf(request.getParameter("rows")));
		sqlMap.put("deleted", false);
		sqlMap.put("sellerId",sellerId);
		sqlMap.put("orderByKey", "-ct");
		Page<Order> page = orderService.page(sqlMap);// 组装page对象
		
		List<SellerOrderListDto>result=Lists.newArrayList();
		for (Order o : page.getData()) {
			result.add(new SellerOrderListDto(o));
		}
		JsonPageUtils.renderJsonPage(page.getTotal(),result,
				response);
	}
	@RequestMapping("/ticketList")
	public void ticketList(
			@Param("start")String start,
			@Param("end")String end,
			@Param("status")String status,
			HttpServletRequest request,HttpServletResponse response){
		Map<String, Object> sqlMap = QueryParamUtils.builderQueryMap(request);// 组装查询参数
		Long sellerId=(Long)request.getSession().getAttribute(AdminSessionConstant.SHOP_ID);
		try {
			if (StringUtils.isNotBlank(start)) {
				sqlMap.put("ct >", DF.FORMAT_YYYY_MM_dd.parse(start).getTime());
			}
			if (StringUtils.isNotBlank(end)) {
				sqlMap.put("ct <", DF.FORMAT_YYYY_MM_dd.parse(end).getTime());
			}
			if (StringUtils.isNotBlank(status)) {
				sqlMap.put("status", Integer.valueOf(status));
			}
		} catch (ParseException e) {
			logger.error("",e);
		}
		sqlMap.put("pageNo", Integer.valueOf(request.getParameter("page")));
		sqlMap.put("pageSize", Integer.valueOf(request.getParameter("rows")));
		sqlMap.put("deleted", false);
		sqlMap.put("sellerId",sellerId);
		sqlMap.put("orderByKey", "-ct");
		Page<TicketOrder> page = ticketOrderService.page(sqlMap);// 组装page对象
		
		List<SellerOrderListDto>result=Lists.newArrayList();
		for (TicketOrder o : page.getData()) {
			result.add(new SellerOrderListDto(o));
		}
		JsonPageUtils.renderJsonPage(page.getTotal(),result,
				response);
	}
	@RequestMapping("/getItems")
	public void getItems(@RequestParam Long id,HttpServletRequest request,HttpServletResponse response){
		Map<String, Object> sqlMap = QueryParamUtils.builderQueryMap(request);// 组装查询参数
//		Page<Order> page = WebControllerUtils.preparePage(request, 10);// 组装page对象
		sqlMap.put("orderId", id);
		List<OrderItem>temp=itemService.list(sqlMap);
		JsonPageUtils.renderJsonPage(Long.valueOf(temp.size()),temp,
				response);
	}
	@RequestMapping("/getTicketItems")
	public void getTicketItems(@RequestParam Long id,HttpServletRequest request,HttpServletResponse response){
		Map<String, Object> sqlMap = QueryParamUtils.builderQueryMap(request);// 组装查询参数
//		Page<Order> page = WebControllerUtils.preparePage(request, 10);// 组装page对象
		sqlMap.put("orderId", id);
		List<TicketOrderItem>temp=ticketOrderItemService.list(sqlMap);
		JsonPageUtils.renderJsonPage(Long.valueOf(temp.size()),temp,
				response);
	}
	@RequestMapping(value="/deliver" )
	public void deliver(HttpServletRequest request,HttpServletResponse response,
			@RequestParam("id")Long id,
			@RequestParam("name")String name,
			@RequestParam("code")String code){
		Order order = orderService.getById(id);
		if(order!=null && order.getStatus()==OrderConstant.WAIT_SEND){
			order.setExpress(name);
			order.setExpressNo(code);
			order.setSendTime(new Date());
			order.setStatus(OrderConstant.WAIT_RECEIVE);
			orderService.update(order);
			AjaxUtils.renderText(response, "1");
		}else{
			AjaxUtils.renderText(response,"-1");
		}

	}
	@RequestMapping("/useTicket")
	public void useTicket(
			@RequestParam Long orderId,
			@RequestParam String code,
			HttpServletRequest request,HttpServletResponse response){
		try {
			TicketOrder order=ticketOrderService.getById(orderId);
			if (null==order) {
				 AjaxUtils.renderText(response, "找不到该订单！");
				 return;
			}
			if (order.getStatus()!=TicketOrder.status_payed) {
				 AjaxUtils.renderText(response, "该订单未付款或已使用！");
				 return;
			}
			if (!code.toLowerCase().equals(order.getCode().toLowerCase())) {
				 AjaxUtils.renderText(response, "核销码不正确!");
				 return;
			}
			order.setStatus(TicketOrder.status_success);
			incomeRecordService.startIncomeTicket(order.getId());
			ticketOrderService.update(order);
			AjaxUtils.renderText(response, "1");
		}catch (Exception e) {
			logger.error("",e);
		}
	}
}
